package com.why.cachecloud.client.redis.cachecloud.client.lettuce.util.util.codec;

import io.lettuce.core.codec.RedisCodec;

import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class DefaultCodec<T> implements RedisCodec<String, T> {

    private Charset charset = StandardCharsets.UTF_8;

    @Override
    public String decodeKey(ByteBuffer bytes) {
        return charset.decode(bytes).toString();
    }

    @Override
    public T decodeValue(ByteBuffer bytes) {
        byte[] array = new byte[bytes.remaining()];
        bytes.get(array);
        return ProtostuffSerializer.deserialize(array);
    }

    @Override
    public ByteBuffer encodeKey(String key) {
        return charset.encode(key);
    }

    @Override
    public ByteBuffer encodeValue(T value) {
        byte[] byteArray = ProtostuffSerializer.serialize(value);
        return ByteBuffer.wrap(byteArray);
    }
}